package no.la58.scribbles.client.uicomponents;

import java.util.ArrayList;
import java.util.Collections;

import no.la58.scribbles.client.ClientFactory;
import no.la58.scribbles.client.event.ScribblesUpdateEvent;
import no.la58.scribbles.shared.Scribble;
import no.la58.scribbles.shared.ScribbleList;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class ScribbleListView extends Composite implements ScribblesUpdateEvent.UpdateHandler {

    private static ClientFactory clientFactory = GWT.create(ClientFactory.class);
    private static ScribbleListViewUiBinder uiBinder = GWT.create(ScribbleListViewUiBinder.class);

    interface ScribbleListViewUiBinder extends UiBinder<Widget, ScribbleListView> {
    }

    @UiField
    VerticalPanel existingScribbles;

    public ScribbleListView() {
	initWidget(uiBinder.createAndBindUi(this));
	ScribblesUpdateEvent.register(clientFactory.getEventBus(), this);
    }

    @Override
    public void onNewScribbles(ScribbleList scribbles) {
	ArrayList<Scribble> reversed = scribbles.getScribbles();
	Collections.reverse(reversed);
	for (Scribble scribble : reversed) {
	    existingScribbles.insert(new ScribbleView(scribble), 0);
	}

    }

}
